<?php

namespace app\mall\controller\api\uc\car;


use app\mall\enum\YesNoEnum;
use app\mall\exceptions\ApiException;
use app\mall\model\MallGoodsStock;
use app\mall\model\MallUserCar;

class Add extends Base
{

    public function index()
    {
        $post = $this->request->post([
            'goods_stock_id', 'storeId', 'nums', 'type'
        ]);

        $validate = \think\facade\Validate::rule([
            'goods_stock_id' => 'require|integer',
            'storeId' => 'require|integer',
            'nums' => 'integer|gt:0',
        ]);
        if (!$validate->batch(true)->check($post)) {
            ApiException::throws(ApiException::$validError, $validate->getError());
        }

        $stockId = $post['goods_stock_id'];
        $stock = MallGoodsStock::find($stockId);
        if (!$stock) {
            ApiException::throws(ApiException::$infoNotFound);
        }
        $model = MallUserCar::where('uid', $this->getUid())
            ->where('goods_stock_id', $stockId)
            ->where('store_id', $post['storeId'])
            ->find();

        $type = isset($post['type']) && ($post['type'] == 'set') ? 'set' : 'add';

        $nums = $model && ($type == 'add') ? $post['nums'] + $model->nums : $post['nums'];
        if ($stock->stock < $nums) {
            ApiException::throws(ApiException::$goodsStockError);
        }

        if ($model) {
            $model->nums = $nums;
            $rs = $model->save();
        } else {
            $post['uid'] = $this->getUid();
            $post['goods_id'] = $stock->goods_id;
            $model = new MallUserCar($post);
            $rs = $model->save();
        }
        return $this->handleResponse($rs);
    }

}